<template>
  <div>
    <div class="game-warp">
      <iframe
        v-if="url"
        id="iframe"
        ref="iframeView"
        :src="url"
        class="iframe-box"
        frameborder="0"
        :allowfullscreen="true"
        :webkitallowfullscreen="true"
        :mozallowfullscreen="true"
      ></iframe>
    </div>
    <div class="tabbar-box row-space-around">
      <div
        v-for="(item, index) in tabbarList"
        :key="item.key"
        class="column-center all-center tabbar-item"
        @click="onChange(index)"
      >
        <van-image class="image" fit="contain" :src="index === active ? item.activeImage : item.image"></van-image>
        <span :class="{ active_span: index === active }">{{ item.title }}</span>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import { GAME_TYPE, IFRAME_POST_MESSAGE_TO_LOTTERY_TYPE, ON_LOTTERY_POST_MESSAGE_TYPE } from '@/types/game.types.ts'
import { useGameStore } from '@/store/game'
import gameApi from '@/api/game'
import type { PlayLotteryPageQuery } from '@/types/game.types'
import homeImg from '@/assets/images/game/home.png'
import homeActiveImg from '@/assets/images/game/home_active.png'
import rechargeImg from '@/assets/images/game/recharge.png'
import rechargeActiveImg from '@/assets/images/game/recharge_active.png'
import chatImg from '@/assets/images/game/chat.png'
import chatActiveImg from '@/assets/images/game/chat_active.png'
import myImg from '@/assets/images/game/my.png'
import myActiveImg from '@/assets/images/game/my_active.png'
import betImg from '@/assets/images/game/bet.png'

enum TAB_BAR_OPTIONS {
  home = 'home',
  recharge = 'recharge',
  bet = 'bet',
  chat = 'chat',
  my = 'my',
}
definePageMeta({
  layout: false,
  ssr: false,
})
const route = useRoute()
const gameStore = useGameStore()
const iframeView = ref('')

const active = ref(2)
const pageQuery: PlayLotteryPageQuery = {
  id: route.query.id as string,
  game_company_code: route.query.game_company_code as string,
  type: route.query.type as GAME_TYPE,
  code: route.query?.code as string,
  from: route.query?.from as string,
}

const url = ref('')

const tabbarList = [
  { title: '首页', key: TAB_BAR_OPTIONS.home, image: homeImg, activeImage: homeActiveImg },
  { title: '充值', key: TAB_BAR_OPTIONS.recharge, image: rechargeImg, activeImage: rechargeActiveImg },
  { title: '投注', key: TAB_BAR_OPTIONS.bet, image: betImg, activeImage: betImg },
  { title: '聊天', key: TAB_BAR_OPTIONS.chat, image: chatImg, activeImage: chatActiveImg },
  { title: '我的', key: TAB_BAR_OPTIONS.my, image: myImg, activeImage: myActiveImg },
]

const login = async () => {
  if (!pageQuery.id) return

  // TODU: 这里进彩票可能会直接返回首页
  const allGameRes = await gameApi.getGameByCompanyCode({ company_code: 'JCP' })
  if (!Object.keys(allGameRes.data).includes(pageQuery.code)) {
    navigateTo('/')
    return
  }
  const res = await gameApi.login({ game_id: Number(pageQuery.id), game_company_code: '' })
  url.value = res.data.url
  setTimeout(() => {
    iframeView.value.addEventListener('load', () => {
      sendMessage(IFRAME_POST_MESSAGE_TO_LOTTERY_TYPE.major)
    })
  }, 10)
}

const updateURLParameter = (url: string, paramName: string, paramValue: string): string => {
  const baseUrl = window.location.origin
  const newUrl = new URL(url, baseUrl)
  newUrl.searchParams.set(paramName, paramValue)
  return newUrl.search.toString()
}

const changeGame = (data: { type: ON_LOTTERY_POST_MESSAGE_TYPE.ChangeLottryGame; lotteryCode: string }) => {
  const search = updateURLParameter(window.location.search, 'code', data.lotteryCode)
  const url = `${location.origin}${location.pathname}${search}`
  history.replaceState(null, null, url) // 替换地址栏
}

const outGame = () => {
  const needGameOut = gameStore.list.find((game: any) => game.type === pageQuery.type)
  if (pageQuery.id && url.value && needGameOut) {
    gameApi.gameOut({ game_id: Number(pageQuery.id) })
  }
}
const sendMessage = (type: IFRAME_POST_MESSAGE_TO_LOTTERY_TYPE) => {
  iframeView.value.contentWindow.postMessage(JSON.stringify({ type }), new URL(url.value).origin)
}
const onChange = (index: number) => {
  active.value = index
  const routeMap: Record<TAB_BAR_OPTIONS, Function> = {
    [TAB_BAR_OPTIONS.home]: () => navigateTo('/'),
    [TAB_BAR_OPTIONS.recharge]: () => navigateTo('/'),
    [TAB_BAR_OPTIONS.bet]: () => sendMessage(IFRAME_POST_MESSAGE_TO_LOTTERY_TYPE.major),
    [TAB_BAR_OPTIONS.chat]: () => sendMessage(IFRAME_POST_MESSAGE_TO_LOTTERY_TYPE.chat),
    [TAB_BAR_OPTIONS.my]: () => navigateTo('/setting'),
  }
  routeMap[tabbarList[index].key]()
}

const onWebViewMsgPostEvent = (event: any) => {
  const data = typeof event.data === 'string' && JSON.parse(event.data)
  if (data) {
    const fnMap: Record<ON_LOTTERY_POST_MESSAGE_TYPE, Function> = {
      [ON_LOTTERY_POST_MESSAGE_TYPE.login]: () => login,
      [ON_LOTTERY_POST_MESSAGE_TYPE.focus]: () => null,
      [ON_LOTTERY_POST_MESSAGE_TYPE.blur]: () => null,
      [ON_LOTTERY_POST_MESSAGE_TYPE.ChangeLottryGame]: () => changeGame(data),
      [ON_LOTTERY_POST_MESSAGE_TYPE.ExitLottery]: () => navigateTo('/'),
    }
    fnMap[data.type as ON_LOTTERY_POST_MESSAGE_TYPE]()
  }
}

onBeforeUnmount(() => {
  outGame()
})
onMounted(() => {
  login()
  window.addEventListener('beforeunload', () => {
    outGame()
  })
  window.addEventListener('message', onWebViewMsgPostEvent)
})
</script>

<style scoped lang="scss">
.game-warp {
  background: #f2f4fd;
  width: 100%;
  height: 100vh;

  .iframe-box {
    width: 100%;
    height: 100%;
    height: calc(100vh - 100px);
  }
}

.tabbar-box {
  width: 100%;
  height: 90px;
  background: #f2f4fd;
  position: fixed;
  bottom: 0;
  left: 0;

  .tabbar-item {
    &:nth-of-type(3) {
      .image {
        width: 72px;
        height: 86px;
        transform: translateY(-20%);
      }

      span {
        margin-top: -20px;
        margin-left: 10px;
      }
    }
    .image {
      width: 54px;
      height: 54px;
      fill: #a0b0db;
    }
    span {
      margin-top: 2px;
      color: #74739c;
      margin-right: 10px;
      font-size: 20px;
      font-weight: 400;
    }

    .active_span {
      color: #5d5fef;
    }
  }
}
</style>
